import networkx as nx
import numpy as np
np.random.seed(1)
N = 1000
# %%
def write2File(G,filename,n):
    """
    将图G输出为文本数据,格式为
    u,v,weight
    """
    with open(filename, 'w') as f:
        f.write(f"{n}\n") #首先输出矩阵的大小,从0到n-1个节点
        for u, v, data in G.edges(data=True):
            weight = data['weight']
            f.write(f"{u},{v},{weight}\n")
        f.write('-'*10)
        f.write('\n')
        match = nx.max_weight_matching(G)
        # 0表示 False ,1 表示 True
        weight = 0
        for key in match:
            key = sorted(key)
            weight += G[key[0]][key[1]]['weight']
        f.write(f"{weight}\n")
        pass
        
            
# %%
def createG(n,p,seed):
    """
    创建图G,必须是无向图
    """
    # 定义两个集合的节点
    top_nodes = list(range(n))
    bottom_nodes = list(range(n,2*n))

    # 创建一个空的二分图
    G = nx.Graph()

    # 添加两个集合的节点
    G.add_nodes_from(top_nodes, bipartite=0)
    G.add_nodes_from(bottom_nodes, bipartite=1)

    # 随机添加边和权重
    for u in top_nodes:
        for v in bottom_nodes:
            weight = np.random.randint(1, 100)  # 权重随机赋值为1到10之间的整数
            G.add_edge(u, v, weight=weight)

    return G


# %%
if __name__ == "__main__":
    for i in range(N):
        n = np.random.randint(3,8)
        
        p = np.random.rand(1)/10 + 0.01 # 最大匹配这里用不上
        seed = np.random.randint(1, 1000000000)

        G = createG(n, p, seed)
        filename = "MaxMatchData/graph_" + str(i) + ".txt"
        write2File(G, filename,n)

